package trans.service;

import java.util.Date;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import trans.action.support.PageMode;
import trans.model.Sa;
import trans.model.SaComment;
import trans.support.Constants;
import trans.utils.HibernateUtil;

public class SaCommentDAO{
	
	public static void addComment(SaComment newComment,boolean customerComment){
		newComment.setCreateTime(new Date());
		HibernateUtil.saveOrUpdate(newComment);
		
		Sa sa = 
			(Sa) HibernateUtil.get(Sa.class, newComment.getSaId());
		if(customerComment){
			if(sa.getFlagRead() == Constants.STATUS_SA_NONE){
				sa.setFlagRead(Constants.STATUS_SA_NEEDHAND);
			}
		}else{
			if(sa.getFlagRead() == Constants.STATUS_SA_NEEDHAND){
				sa.setFlagRead(Constants.STATUS_SA_HANDED);
			}
		}
		HibernateUtil.saveOrUpdate(sa);
	}
	
	@SuppressWarnings("unchecked")
	public static void fillCommentPage(PageMode pm) {
		Criteria criteria =
			 HibernateUtil.getSession().createCriteria(SaComment.class);
		Integer saId = (Integer) pm.getParam(SaComment.PROP_SA_ID);
		criteria.add(Restrictions.eq(SaComment.PROP_SA_ID, saId) );
		criteria.setFirstResult(pm.getOffset());
		criteria.setMaxResults(pm.getMaxPageItems());
		criteria.addOrder(Order.desc(SaComment.PROP_ID));
		pm.setDatas(criteria.list());
		
		criteria =  HibernateUtil.getSession().createCriteria(SaComment.class); 
		criteria.add(Restrictions.eq(SaComment.PROP_SA_ID, saId) );
		Long count = 
			(Long) criteria.setProjection(Projections.rowCount()).uniqueResult(); 
		pm.setTotal(count);
	}

}
